<?php

namespace App\Http\Controllers\Admin\UserManager;

use App\Jobs\ExampleJob;
use App\Enums\ExportEnum;
use App\Jobs\QiPao\ExcelJob;
use App\Services\Tools\Export;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

//引用http请求类
use App\Response\Response;
use Illuminate\Support\Facades\Validator;

class BackpackGiftController extends BaseController
{

    /**
     * @api {post} /user-manager/backpack-gift/freeze 背包礼物冻结解冻
     * @apiVersion 0.1.0
     * @apiName 会员管理-背包礼物创建解冻
     * @apiGroup 会员管理
     * @apiParam {number} id
     * @apiParam {number} state                            1正常2冻结
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function freeze(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'id' => 'required|integer',
                'state' => 'required|numeric|integer|in:1,2',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $params = $request->input();
        $id = $params['id'];

        $res = app('repo_user');

        $rows = $res->freezeBackpackGift($id, $params);
        if (!$rows) {
            throw new BasicException(10001, "冻结失败！");
        }

        return Response::sendData(true);
    }

    //批量冻结

    /**
     * @api {post} /user-manager/backpack-gift/vast-freeze 批量冻结背包礼物
     * @apiVersion 0.1.0
     * @apiName 会员管理-批量冻结背包礼物
     * @apiGroup 会员管理
     * @apiParam {string} ids                       冻结礼物id组成的字符串 例如 1,2,34
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function vastFreeze(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'ids' => 'required|string',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $ids = $request->input('ids');
        $ids = explode(',', $ids);
        $ids = array_unique($ids);
        $res = app('repo_user');

        $rows = $res->vastFreezeBackpackGift($ids);
        if (!$rows) {
            throw new BasicException(10001, "冻结失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {delete} /user-manager/backpack-gift 背包礼物删除
     * @apiVersion 0.1.0
     * @apiName 会员管理-背包礼物删除
     * @apiGroup 会员管理
     * @apiParam {string} ids                       字符串分割的id 必传
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function del(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'ids' => 'required|string',
            ]);
        } catch (\Exception $e) {
            $err = $e->errors();
            //throw new BasicException(10001, json_encode($e->errors()));
            throw new BasicException(10001, $err['ids'][0]);
        }

        $idsStr = $request->input("ids");
        $idsArr = explode(",", $idsStr);

        $rows = app('repo_user')->delBackpackGift($idsArr);
        if (!$rows) {
            throw new BasicException(10001, "删除失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {get} /user-manager/backpack-gift 背包礼物列表
     * @apiVersion 0.1.0
     * @apiName 会员管理-背包礼物列表
     * @apiGroup 会员管理
     * @apiParam {number} user_code 用户编号 可选
     * @apiParam {number} price_order  价格排序方式 可选   1升 2降  不传按id倒叙
     * @apiParam {number} gift_id 礼物id 可选
     * @apiParam {string} nickname 用户昵称 可选
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "id(序号)": 519255,
     * "gift_id(礼物id)": 82,
     * "number(礼物数量)": 98,
     * "state(1正常2冻结)": 1,
     * "nickname(用户昵称)": "泡神",
     * "user_code(用户编号)": 285912,
     * "name(礼物名称)": "海豚池",
     * "price(礼物价格)": 1000
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 10,
     * "next": null,
     * "total": 1
     * }
     * }
     * }
     * }
     */
    public function list(Request $request)
    {
        //参数校验
        //        try {
        $validator = Validator::make($request->all(), [
            'price_order' => 'filled|in:1,2',//1升序 2降序
            'user_code'   => 'filled|numeric',
            'gift_id'     => 'filled|numeric',
            'nickname'    => 'filled|string',
            'perPage'     => 'filled|numeric',
            'page'        => 'filled|numeric',
        ], [
            'nickname.filled'   => '用户昵称不能为空',
            'nickname.string'   => '用户昵称必须为字符串',
            'user_code.filled'  => '用户ID不能为空',
            'user_code.numeric' => '用户ID必须为数字',
        ]);
        if ($validator->fails()) {
            throw new BasicException(10001, $validator->errors()->first());
        }


        $list = app('repo_user')->getUserBackpackQueryList($request->input());


        return Response::sendList($list);
    }

    /**
     * @api {get} /user-manager/backpack-gift/excel 表格导出功能背包礼物
     * @apiVersion 0.1.0
     * @apiName 会员管理-表格导出功能背包礼物
     * @apiGroup 会员管理
     * @apiParam {number} user_code 用户编号 可选
     * @apiParam {number} gift_id 礼物id 可选
     * @apiParam {string} nickname 用户昵称 可选
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "uri": "asdasdasd.com"
     * }
     */
    public function backpackGiftToExcel(Request $request)
    {
        //        $res = app('repo_get_data_to_excel')->createZipFile('D:\qipaostar\admin\qipao-manage-api/storage/excel/20211008-191957_2503', "D:\qipaostar\admin\qipao-manage-api/storage/excel/20211008-191957_2503/user_backpack_gift.zip");
        //        die();
        //参数校验
        //        try {
        $validator = Validator::make($request->all(), [
            'user_code' => 'filled|numeric',
            'gift_id'   => 'filled|numeric',
            'nickname'  => 'filled|string',
            'perPage'   => 'filled|numeric',
            'page'      => 'filled|numeric',
        ], [
            'nickname.filled'   => '用户昵称不能为空',
            'nickname.string'   => '用户昵称必须为字符串',
            'user_code.filled'  => '用户ID不能为空',
            'user_code.numeric' => '用户ID必须为数字',
        ]);

        if ($validator->fails()) {
            throw new BasicException(10001, $validator->errors()->first());
        }

        $list = app('repo_user')->getAllUserBackpackGift($request->input());

        $fields = [
            ['field' => 'id', 'header' => '序号', 'width' => '18'],
            ['field' => 'user_code', 'header' => '用户id', 'width' => '18'],
            ['field' => 'nickname', 'header' => '用户昵称', 'width' => '18'],
            ['field' => 'name', 'header' => '礼物名称', 'width' => '18'],
            ['field' => 'price', 'header' => '礼物价格（金币）', 'width' => '18'],
            ['field' => 'number', 'header' => '礼物数量', 'width' => '18'],
        ];
        $downloadUrl = Export::exportUsePhpOffice('user_backpack_fift', $fields, $list);
        app('model_admin_export_log')->add(23, $request->input(), $downloadUrl);

        return Response::sendData(['uri' => $downloadUrl]);
    }

    /**
     * @api {get} /user-manager/backpack-gift/excel/async 异步表格导出功能背包礼物
     * @apiVersion 0.1.0
     * @apiName 异步表格导出功能背包礼物
     * @apiGroup 会员管理
     * @apiParam {number} user_code 用户编号 可选
     * @apiParam {number} gift_id 礼物id 可选
     * @apiParam {string} nickname 用户昵称 可选
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "uri": "asdasdasd.com"
     * }
     */
    public function asyncToEccel(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'user_code' => 'filled|numeric',
            'gift_id'   => 'filled|numeric',
            'nickname'  => 'filled|string',
            'perPage'   => 'filled|numeric',
            'page'      => 'filled|numeric',
        ], [
            'nickname.filled'   => '用户昵称不能为空',
            'nickname.string'   => '用户昵称必须为字符串',
            'user_code.filled'  => '用户ID不能为空',
            'user_code.numeric' => '用户ID必须为数字',
        ]);
        $data = [
            'admin_id'     => $request->admin_id ?? '',
            'data_no'      => 23,
            'condition'    => json_encode($request->input()) ?? '',
            'status'       => 0,//正在导出
            'title'        => '用户背包 异步导出',//正在导出
            'download_url' => '',
        ];
        $exportLogId = app('model_admin_export_log')->insertGetId($data);
        $excel = new ExcelJob($exportLogId, $request->admin_id, 23, $request->only(['user_code', 'gift_id', 'nickname']));
        // 标记导出程序开始运行
        dispatch($excel)->onQueue(env('RABBITMQ_QUEUE_EXCEL'));  //推送到指定队列

        return Response::sendData(true);
    }

    /**
     * @api {get} /user-manager/backpack-gift/give/gift 送礼纪录
     * @apiVersion 3.6.3
     * @apiName 送礼纪录
     * @apiGroup 会员管理
     * @apiParam {number} gift_id 礼物id 可选
     * @apiParam {string} user_code_rec 收礼人id 可选
     * @apiParam {string} user_code 用户code码 可选
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "current_page": 1,
     * "data": [
     * {
     * "id": 8935,
     * "user_id": 553082,
     * "user_code（送礼用户id）": 217064,
     * "nickname（送礼用户昵称）": "哥古古怪怪",
     * "money（送礼用户余额）": "599900702.00",
     * "gift_id（礼物id）": 325,
     * "number": 1,
     * "gift_name（礼物名称）": "狗粮",
     * "to_user_id（收礼用户id）": 1318344,
     * "to_user_code（收礼用户code'）": 9427099,
     * "to_nickname（收礼用户昵称）": "小气泡9427099",
     * "total_price(送礼价值)": "666.00",
     * "add_time（创建时间）": "2021-11-25 16:47:46"
     * }
     * ],
     * "total": 37
     * },
     * "message": ""
     * }
     */
    public function userGiveGiftLog(Request $request)
    {
        $param = $request->only('user_code', 'user_code_rec', 'gift_id', 'sort', 'perPage', 'page');
        $validator = Validator::make($param, [
            'user_code'     => 'filled|numeric',
            'user_code_rec' => 'filled|numeric',//收礼人id
            'gift_id'       => 'filled|numeric',
            'perPage'       => 'filled|numeric',
            'page'          => 'filled|numeric',
            'sort'          => 'filled|in:1,2',
        ]);

        if ($validator->fails()) {
            throw new BasicException(10001, $validator->errors()->first());
        }

        $perPage = $param['perPage'] ?? 20;
        $page = $param['page'] ?? 1;
        $model = app('model_give_gift')
            ->select(['id', 'user_id', 'gift_id', 'gift_user', 'number', 'total_price', 'add_time'])
            ->with([
                'user'       => function ($query) {
                    $query->select(['user_id', 'money']);
                },
                'user_give'  => function ($query) {
                    $query->select(['user_id', 'user_code', 'nickname']);
                },
                'user_given' => function ($query) {
                    $query->select(['user_id', 'user_code', 'nickname']);
                },
                'gift'       => function ($query) {
                    $query->select(['id', 'name']);
                },
            ]);
        $where = [];
        if (isset($param['user_code'])) {
            $UserData = app('model_user_data')->select('user_id')->where('user_code', $param['user_code'])->first();

            if (empty($UserData)) {
                $where[] = ['user_id', '=', -1];
            } else {
                $where[] = ['user_id', '=', $UserData->user_id];
            }
        }

        if (isset($param['user_code_rec'])) {
            $UserData = app('model_user_data')->select('user_id')->where('user_code', $param['user_code_rec'])->first();
            if (empty($UserData)) {
                $where[] = ['gift_user', '=', -1];
            } else {
                $where[] = ['gift_user', '=', $UserData->user_id];
            }
        }

        if (isset($param['gift_id'])) {
            $where[] = ['gift_id', '=', $param['gift_id']];
        }

        if (isset($param['sort'])) {
            $sort = $param['sort'] == 1 ? 'asc' : 'desc';
            $model = $model->orderBy('total_price', $sort);
        } else {
            $model = $model->orderBy('id', 'desc');
        }

        if (empty($where)) {
            $minId = app('model_give_gift')->orderBy('id','asc')->pluck('id')->first();
            $maxId = app('model_give_gift')->orderBy('id','desc')->pluck('id')->first();
            $endId = $maxId - ($page - 1) * $perPage;
            $startId = $endId - $perPage;
            $wherePage = [['id', '>', $startId], ['id', '<=', $endId]];
            $result['data'] = $model->where($wherePage)->get()->toArray();
            $result['total'] = $maxId - $minId + 1;
        } else {
            $result = $model->where($where)->paginate($perPage, ['*'], '', $page)->toArray();
        }


        $temp = [];

        foreach ($result['data'] as $key => $value) {
            $temp[$key]['id'] = $value['id'];
            $temp[$key]['user_id'] = $value['user_id'];
            $temp[$key]['user_code'] = $value['user_give']['user_code'];
            $temp[$key]['nickname'] = $value['user_give']['nickname'];
            $temp[$key]['money'] = $value['user']['money'];
            $temp[$key]['gift_id'] = $value['gift_id'];
            $temp[$key]['gift_name'] = $value['gift']['name'];

            $temp[$key]['to_user_id'] = $value['gift_user'];
            $temp[$key]['to_user_code'] = $value['user_given']['user_code'];
            $temp[$key]['to_nickname'] = $value['user_given']['nickname'];
            $temp[$key]['number'] = $value['number'];

            $temp[$key]['total_price'] = $value['total_price'];
            $temp[$key]['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
        }


        return Response::sendData(['data' => $temp, 'total' => $result['total']]);
    }

}
